package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;


    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {

        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();

            boolean flag = false;
            HttpServlet httpServlet = null;
            for (Mapper.Service service : mapper.getServiceList()) {
                Mapper.Engine engine = service.getEngine();
                for (Mapper.Host host : engine.getHostList()) {
                    for (Mapper.Context context : host.getContextList()) {
                        for (Mapper.Wrapper wrapper : context.getWrapperList()) {
                            if (wrapper.getUrl().equals(url)) {
                                flag = true;
                                httpServlet = wrapper.getHttpServlet();
                            }
                        }
                    }
                }
            }
            // 静态资源处理
            if (!flag) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}



